using B.S.XZYData.Api.Wrter.Application.Command.Team;
using B.S.XZYData.Domain.XZY;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure;
using MediatR;

namespace B.S.XZYData.Api.Wrter.Application.Handler.Team
{
    /// <summary>
    /// 添加班组处理器
    /// </summary>
    public class AddTeamHandler : IRequestHandler<AddTeamCommand, ApiResult<bool>>
    {
        private readonly MyDbContext _dbContext;

        public AddTeamHandler(MyDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task<ApiResult<bool>> Handle(AddTeamCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 生成班组编码（如果未提供）
                if (string.IsNullOrEmpty(request.TeamCode))
                {
                    request.TeamCode = GenerateTeamCode();
                }

                // 创建班组
                var team = new B.S.XZYData.Domain.XZY.Team
                {
                    TeamName = request.TeamName,
                    TeamCode = request.TeamCode,
                    TeamType = request.TeamType,
                    Remark = request.Remark,
                    CreateTime = DateTime.Now,
                    CreatorId = 1, // 这里应该从当前登录用户获取
                    IsDeleted = false
                };

                // 插入班组
                var teamId = await _dbContext.Insertable(team).ExecuteReturnBigIdentityAsync();

                // 添加班组成员
                if (request.TeamMembers != null && request.TeamMembers.Any())
                {
                    var teamMembers = request.TeamMembers.Select(member => new B.S.XZYData.Domain.XZY.TeamMember
                    {
                        TeamId = (int)teamId,
                        MemberName = member.MemberName,
                        MemberRealName = member.MemberRealName,
                        Phone = member.Phone,
                        CreateTime = DateTime.Now,
                        CreatorId = 1, // 这里应该从当前登录用户获取
                        IsDeleted = false
                    }).ToList();

                    await _dbContext.Insertable(teamMembers).ExecuteCommandAsync();
                }

                return new ApiResult<bool>
                {
                    Code = ApiEnum.Success,
                    Msg = "添加班组成功",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool>
                {
                    Code = ApiEnum.Error,
                    Msg = $"添加班组失败: {ex.Message}",
                    Data = false
                };
            }
        }

        /// <summary>
        /// 生成班组编码
        /// </summary>
        private string GenerateTeamCode()
        {
            var date = DateTime.Now.ToString("yyyyMMdd");
            var random = new Random();
            var randomNum = random.Next(1000, 9999);
            return $"BZ{date}{randomNum}";
        }
    }
}
